#ifndef PERFRUNPLANFILEDAO_H_
#define PERFRUNPLANFILEDAO_H_

#include "Substitution.hpp"
#include "Plan.hpp"

#include <utility>
#include <string>
#include <vector>
#include <map>

#include <boost/algorithm/string/trim.hpp>
#include <boost/tokenizer.hpp>

#include <sstream>
#include <iostream>

namespace fixstoker {

class PlanFileDao {
public:
	PlanFileDao();
	virtual ~PlanFileDao();

	/*virtual*/ const Plan* load(const char* fileName) const;

//	template<typename StreamT>
	const Plan* load(std::istringstream& input) {
		using namespace std;
		using namespace boost;

		Plan* result = new Plan();

		typedef vector< string > split_vector_type;

		bool isParsingMsgTemplates = true;
		string line;
		vector<string> tokens;

		this->codeToIndexMap_.clear();

		while (getline(input, line)) {
			trim(line);

			if (0 == line.length() || '#' == line[0]) {
				continue; // skip comments and empty lines
			}

			tokens.clear();
			splitLine(line, &tokens);

			if ("template" != tokens[0]) {
				isParsingMsgTemplates = false;
			}

			if (isParsingMsgTemplates) {
				this->loadTemplate(tokens, result);
			} else {
				this->loadEntry(tokens, result);
			}
		}

		return result;
	}

private:
	void splitLine(const std::string& line, std::vector<std::string>* outVector) const;
	void loadTemplate(const std::vector<std::string>& tokens, Plan* plan);
	void loadEntry(const std::vector<std::string>& tokens, Plan* plan);
	Substitution* loadSubstitution(std::string str);

	std::map<std::string, int> codeToIndexMap_;
	std::vector<std::string> substitutionTokensTmp_;
};

}

#endif /* PERFRUNPLANFILEDAO_H_ */
